package members

import (
	"encoding/json"
	"github.com/sideshow/apns2/certificate"
	"github.com/sideshow/apns2"
	"adai.design/homeserver/log"
	"crypto/tls"
	"adai.design/homeserver/db"
)

const (
	APNSTopic = "adai.design.home"
)

type APNSAlert struct {
	Title 	string		`json:"title"`
	Body 	string		`json:"body"`
}

func (aps *APNSAlert) String() string {
	buf, _ := json.Marshal(aps)
	return string(buf)
}

var APNSCert = func() *tls.Certificate {
	cert, err := certificate.FromP12File("conf/apns.p12", "clouds")
	if err != nil {
		return nil
	}
	return &cert
}()

func PushNotificationToMember(id string, aps *APNSAlert) error {
	membership := db.GetMembershipById(id)
	for _, c := range membership.Clients {
		if !(c.DevType == db.MembershipClientTypePhone ||
			c.DevType == db.MembershipClientTypePad ||
			c.DevType == db.MembershipClientMacbook) ||
			c.APNS == "" {
			continue
		}

		log.Debug("membership(%s) apns(%s)", id, c.APNS)
		notification := &apns2.Notification{
			DeviceToken: c.APNS,
			Topic: APNSTopic,
		}
		c.Badge += 1
		info := map[string]interface{}{
			"aps": map[string]interface{}{
				"alert": map[string]interface{}{
					"title": aps.Title,
					"body": aps.Body,
				},
				"category":"GENERAL",
				"badge": c.Badge,
				"sound":"default",
			},
		}
		notification.Payload, _ = json.Marshal(info)
		client := apns2.NewClient(*APNSCert).Development()
		res, err := client.Push(notification)
		if err != nil {
			log.Error("result err:", err)
		}
		log.Debug("result code(%v) apnsId(%v) reason(%v)", res.StatusCode, res.ApnsID, res.Reason)
	}
	return nil
}



